import createAxios from '../utils/axios'


//获取汇率列表
export const getRateList = () => {
  return createAxios({
      url: `/api/exchange/rate/list`,
      method: 'GET',
  }, 'API1');
}
// // 获取人机验证秘钥接口
// export const getSetting = () => {
//   return createAxios({
//       url: '/shop/common/setting',
//       method: 'GET',
//   },'API1');
// }
//获取地图信息
export const getMapInfo = (params: any) => {
  return createAxios({
      url: `/api/map/index?page=${params.page}&page_size=${params.page_size}&address=${params.address}`,
      method: 'GET',
  }, 'API1');
}
//获取地图信息
export const getGoogleMap = (params: any) => {
  return createAxios({
      url: `/api/map/google/address?page=${params.page}&page_size=${params.page_size}&address=${params.address}`,
      method: 'GET',
  }, 'API1');
}
// 获取首页
export const getHomeConfig = () => {
  return createAxios({
      url: `shop/classify/getHomeConfig`,
      method: 'GET',
  }, 'API1');
}
// 获取更多探索
export const getHomeCategory = () => {
  return createAxios({
      url: `shop/classify/getHomeCategory`,
      method: 'GET',
  }, 'API1');
}

/**
 * 获取穿搭列表
 * @param params 
 * @param params.page 页码
 * @param params.page_size 每页条数
 * @param params.type 类型  1-图片，2-视频  
 * @returns 
 */
export const getLookList = (params: any) => {
  return createAxios({
      url: `/api/look`,
      method: 'GET',
      params
  }, 'API1');
}

/**
 * 获取穿搭详情
 * @param params 
 * @param params.id 穿搭id
 * @returns 
 */
export const getLookDetail = (params: any) => {
  return createAxios({
      url: `/api/looks/read`,
      method: 'GET',
      params
  }, 'API1');
}

// 邮箱发送验证码
export const getSendCode = (email: number) => {
  // 返回的数据格式可以和服务端约定
  return createAxios({
      url: `/api/signin/auth/code/send?email=${email}`,
      method: 'GET',
  }, 'API1');
}
// 验证邮箱
export const postVerifyEmail = (params: any) => {
  return createAxios({
      url: `/api/email/verifyEmail`,
      method: 'POST',
      data: params,
  }, 'API1');
}
//验证邮箱发送验证码
export const postSendEmailCode = (params: any) => {
  return createAxios({
      url: `/api/email/sendEmailCode`,
      method: 'POST',
      data: params,
  }, 'API1');
}
// 配置信息
export const getSetting = () => {
  return createAxios({
      url: '/shop/common/setting',
      method: 'GET',
  },'API1',{loading:false});
}
/**
 * 将文件转换为Base64
 * @param file 文件对象
 * @returns Promise<string> Base64字符串
 */
export const fileToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = error => reject(error)
  })
}

/**
 * 验证文件
 * @param file 文件对象
 * @param options 验证选项 {maxSize, accept}
 * @returns string | null 错误信息或null
 */
export const validateFile = (file: File, options: { maxSize?: number, accept?: string } = {}): string | null => {
  const { maxSize = 5, accept = 'image/*' } = options

  // 检查文件类型
  if (!file.type.match(accept.replace('*', '.*'))) {
    return 'File type not supported'
  }

  // 检查文件大小
  if (file.size > maxSize * 1024 * 1024) {
    return `File size cannot exceed ${maxSize}MB`
  }

  return null
}

/**
 * 上传单个图片并转换为Base64
 * @param file 图片文件
 * @param onProgress 进度回调
 * @returns Promise<{ base64: string; response: any }> Base64和上传响应
 */
export const uploadImageWithBase64 = async (
  file: File,
  onProgress?: (progress: number) => void
): Promise<{ base64: string; response: any }> => {
  // 验证文件
  const error = validateFile(file, { accept: 'image/*' })
  if (error) {
    throw new Error(error)
  }

  // 转换为Base64
  const base64 = await fileToBase64(file)

  try {
    // 调用上传API
    const response = await createAxios({
      url: '/api/base64/upload',
      method: 'POST',
      data: { base64 },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total && onProgress) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          onProgress(progress)
        }
      }
    }, 'API1', { 
      loading: false,
      // 禁用自动显示消息提示，避免重复提示
      code_message_show: false,
      error_message_show: false 
    })

    // 检查返回格式是否符合预期
    if (response && response.code === 1 && response.data && response.data.file && response.data.file.url) {
      // 处理返回的数据，确保返回格式统一
      return { 
        base64, 
        response: {
          ...response,
          url: response.data.file.url // 将 URL 提取到顶层，方便获取
        }
      }
    } else {
      throw new Error('Image upload format error')
    }
  } catch (error) {
    console.error('Upload failed:', error)
    throw new Error(error instanceof Error ? error.message : 'Upload failed')
  }
}

/**
 * 上传多个图片并转换为Base64
 * @param files 图片文件数组
 * @param options 上传选项 {maxSize, maxCount, accept}
 * @param onProgress 进度回调
 * @returns Promise<Array<{ base64: string; response: any }>> Base64和上传响应数组
 */
export const uploadImagesWithBase64 = async (
  files: File[],
  options: { maxSize?: number, maxCount?: number, accept?: string } = {},
  onProgress?: (index: number, progress: number) => void
): Promise<Array<{ base64: string; response: any }>> => {
  const { maxCount = 5 } = options

  // 检查文件数量
  if (files.length > maxCount) {
    throw new Error(`You can upload a maximum of ${maxCount} files`)
  }

  // 验证所有文件
  for (const file of files) {
    const error = validateFile(file, options)
    if (error) {
      throw new Error(error)
    }
  }

  // 上传所有文件
  const uploadPromises = files.map((file, index) =>
    uploadImageWithBase64(file, (progress) => onProgress?.(index, progress))
  )

  return Promise.all(uploadPromises)
}